package com.ruifu.doc.service.impl;

import com.fhzncloud.cloud.admin.api.feign.RemoteDeptService;
import com.fhzncloud.cloud.common.security.service.CloudUser;
import com.ruifu.common.po.DmFold;
import com.ruifu.common.po.DmFoldCont;
import com.ruifu.common.po.ObjectPermissionsAuthorization;
import com.ruifu.common.utils.BeanConverter;
import com.ruifu.common.utils.FindPermissionCommon;
import com.ruifu.common.utils.PermissionObjectType;
import com.ruifu.common.utils.PermissionsUtlis;
import com.ruifu.doc.conf.DocFinal;
import com.ruifu.doc.dto.fold.DmFoldDTO;
import com.ruifu.doc.dto.fold.DmFoldUpdateDTO;
import com.ruifu.doc.mapper.DmFoldContMapper;
import com.ruifu.doc.mapper.DmFoldMapper;
import com.ruifu.doc.mapper.ObjectPermissionsAuthorizationMapper;
import com.ruifu.doc.permissionsObject.FoldPermissionObject;
import com.ruifu.doc.service.DmFoldService;
import com.ruifu.doc.vo.fold.DmFoldVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件夹业务逻辑层
 *
 * @author nyr
 * @create 2019/11/11
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class DmFoldServiceImpl implements DmFoldService {
    @Autowired(required = false)
    private DmFoldMapper dmFoldMapper;

    @Autowired(required = false)
    private DmFoldContMapper dmFoldContMapper;

    @Autowired(required = false)
    private ObjectPermissionsAuthorizationMapper objectPermissionsAuthorizationMapper;

    @Autowired
    DmFoldService dmFoldService;

    @Autowired
    RemoteDeptService remoteDeptService;
    /**
     * 创建文件夹
     *
     * @param dmFoldDTO
     * @param cloudUser
     * @return 文件夹id
     */
    @Override
    public Long insert(DmFoldDTO dmFoldDTO, CloudUser cloudUser) {
        /*DOT转PO*/
        DmFold dmFold = BeanConverter.copyProperties(dmFoldDTO, DmFold.class);
        if(dmFold.getFdType()==null){
            dmFold.setFdType(dmFoldDTO.getSignBoardDoc());
        }
        dmFoldMapper.insert(dmFold, cloudUser);
        return dmFold.getFdFoldId();
    }

    /**
     * 修改文件夹
     *
     * @param dmFoldUpdateDTO
     * @param cloudUser
     */
    @Override
    public void update(DmFoldUpdateDTO dmFoldUpdateDTO, CloudUser cloudUser) {
        //根据id查询文件夹信息
        DmFold dmFold = dmFoldMapper.findById(dmFoldUpdateDTO.getFdFoldId(), cloudUser);
        BeanConverter.copyProperties(dmFoldUpdateDTO, dmFold);
        //存储到数据库
        dmFoldMapper.update(dmFold, cloudUser);
    }

    /**
     * 删除文件夹
     *
     * @param fdFoldId  文件夹id
     * @param cloudUser
     */
    @Override
    public void delete(Long fdFoldId, CloudUser cloudUser,Integer signBoardDoc) {
        this.recursionDelete(fdFoldId, cloudUser,signBoardDoc);
    }

    /**
     * 页面加载查询文件夹列表
     *
     * @param cloudUser
     * @return
     */
    @Override
    public List<DmFoldVO> findList(CloudUser cloudUser,Integer signBoardDoc) {
        //查询顶级文件夹列表
        List<DmFold> dmFoldParentList = dmFoldMapper.findByFdPFoldId(0L, cloudUser,signBoardDoc);
        if(dmFoldParentList==null || dmFoldParentList.size()==0){
                DmFold dmFold = new DmFold();
            if (DocFinal.DOCUMENT_LIBRARY.equals(signBoardDoc)){
                dmFold.setFdName("公共知识库");
                dmFold.setFdRemark("公共知识库");
                dmFold.setFdType(DocFinal.DOCUMENT_LIBRARY);
                getInitialize(cloudUser, dmFoldParentList, dmFold);
            }
            if (DocFinal.PRODUCT_LIBRARY.equals(signBoardDoc)){
                dmFold.setFdName("产品图档库");
                dmFold.setFdRemark("产品图档库");
                dmFold.setFdType(DocFinal.PRODUCT_LIBRARY);
                getInitialize(cloudUser, dmFoldParentList, dmFold);
            }
            if (DocFinal.COLLECT_LIBRARY.equals(signBoardDoc)){
                dmFold.setFdName("我的收藏");
                dmFold.setFdRemark("我的收藏");
                dmFold.setFdType(DocFinal.COLLECT_LIBRARY);
                getInitialize(cloudUser, dmFoldParentList, dmFold);
            }

        }
        //声明总文件夹列表
        List<DmFold> dmFoldList = new ArrayList<>();
        dmFoldParentList.forEach(dmFold -> this.recursionFindSonList(dmFold, dmFoldList, cloudUser,signBoardDoc));
        List<DmFoldVO> dmFoldVoList = BeanConverter.copyList(dmFoldList, DmFoldVO.class);
        //如果是第一次初始化我的收藏文件夹则不进入筛选
        if (dmFoldVoList.size()>1){
            if (DocFinal.COLLECT_LIBRARY.equals(signBoardDoc)){
                List<DmFoldVO> list = new ArrayList<>();
                List<DmFoldVO> myDocList = dmFoldVoList.parallelStream().filter(dmFoldVO -> dmFoldVO.getCreator().equals(cloudUser.getId())).collect(Collectors.toList());
                List<DmFoldVO> docNodeList = dmFoldVoList.parallelStream().filter(dmFoldVO -> dmFoldVO.getFdPFoldId() == 0).collect(Collectors.toList());
                list.addAll(myDocList);
                list.addAll(docNodeList);
                return list.stream().distinct().collect(Collectors.toList());
            }
        }
        for (DmFoldVO dmFoldVO : dmFoldVoList) {
            dmFoldVO.setFoldPermission(this.findPermissionByUserIdAndFold(cloudUser, dmFoldVO.getFdFoldId()));
        }
        return dmFoldVoList;
    }

    private void getInitialize(CloudUser cloudUser, List<DmFold> dmFoldParentList, DmFold dmFold) {
        dmFold.setFdPFoldId(0L);
        dmFold.setFdView(1);
        dmFold.setFdComType("1");
        dmFoldMapper.insert(dmFold,cloudUser);
        dmFoldParentList.add(dmFold);
    }

    /**
     * 递归查询文件夹列表
     *
     * @param dmFold
     * @param dmFoldList
     * @param cloudUser
     */
    private void recursionFindSonList(DmFold dmFold, List<DmFold> dmFoldList, CloudUser cloudUser,Integer signBoardDoc) {
        //添加当前文件夹到集合
        dmFoldList.add(dmFold);
        //查询下级文件夹
        List<DmFold> dmFoldSonList = dmFoldMapper.findByFdPFoldId(dmFold.getFdFoldId(), cloudUser,signBoardDoc);
        //递归
        dmFoldSonList.forEach(dmFoldSon -> this.recursionFindSonList(dmFoldSon, dmFoldList, cloudUser,signBoardDoc));
    }
    /**
     * 递归删除
     *
     * @param fdFoldId  文件夹id
     * @param cloudUser
     */
    private void recursionDelete(Long fdFoldId, CloudUser cloudUser,Integer signBoardDoc) {
        /*删除该文件夹*/
        DmFold dmFold = dmFoldMapper.findById(fdFoldId, cloudUser);
        dmFold.setDelFlag(true);
        dmFoldMapper.update(dmFold, cloudUser);
        /*删除该文件夹下的文件夹内容*/
        //查询该文件夹下的内容集合
        List<DmFoldCont> dmFoldContList = dmFoldContMapper.findByFcFoldId(fdFoldId, cloudUser);
        if (dmFoldContList != null && dmFoldContList.size() != 0) {
            List<Long> fcFoldIdList = new ArrayList<>();
            dmFoldContList.forEach(dmFoldCont -> fcFoldIdList.add(dmFoldCont.getFcId()));
            dmFoldContMapper.batchDelete(fcFoldIdList, cloudUser);
        }
        /*删除下级文件夹*/
        List<DmFold> dmFoldList = dmFoldMapper.findByFdPFoldId(fdFoldId, cloudUser,signBoardDoc);
        dmFoldList.forEach(fold -> this.recursionDelete(fold.getFdFoldId(), cloudUser,signBoardDoc));
    }

    /**
     * 根据文件夹id查询文件夹信息
     *
     * @param fdFoldId
     * @param cloudUser
     * @return
     */
    @Override
    public DmFoldVO findById(Long fdFoldId, CloudUser cloudUser) {
        DmFold dmFold = dmFoldMapper.findById(fdFoldId, cloudUser);
        return BeanConverter.copyProperties(dmFold, DmFoldVO.class);
    }

    /**
     * 文件夹权限
     * @param cloudUser
     * @param fdFoldId
     * @return
     */
    @Override
    public String findPermissionByUserIdAndFold(CloudUser cloudUser, Long fdFoldId) {
        //数据对象
        FoldPermissionObject foldPermissionObject = new FoldPermissionObject();
        DmFold dmFold = dmFoldMapper.findById(fdFoldId, cloudUser);
        foldPermissionObject.dmFold = dmFold;
        foldPermissionObject.permissionsUtlis=new PermissionsUtlis();
        foldPermissionObject.fdFoldId=fdFoldId;
        foldPermissionObject.dmFoldService=new DmFoldServiceImpl();
        foldPermissionObject.permissionsUtlis.remoteDeptService=remoteDeptService;
        //得到文档类型权限定义列表
        List<ObjectPermissionsAuthorization> objectPermissionsList =
                objectPermissionsAuthorizationMapper.findByObjectTypeId(Long.valueOf((PermissionObjectType.FD_TYPE_ID+"")+(dmFold.getFdType()+"")),cloudUser);
        String permission = FindPermissionCommon.findPermissionByUserIdAndPtId(cloudUser, foldPermissionObject, objectPermissionsList);
        log.info(foldPermissionObject.dmFold.getFdName()+"文件夹权限为："+permission);
        return permission;
    }

    /**
     * 被授权对象权限判断函数
     * @param fdFoldId 当前选中的文件夹id
     * @param foIdString  指定的文件夹id集合
     * @return
     */
    @Override
    public Boolean isContain(Long fdFoldId,String foIdString) {
        //文件夹集合
        List<String> foIdList = new ArrayList<>();
        String[] foIdArray = foIdString.split(",");
        for (int i = 0; i < foIdArray.length; i++) {
            foIdList = Arrays.asList(foIdArray[i].split(","));
        }
        if (foIdList.contains(String.valueOf(fdFoldId))){
            return true;
        }
        return false;
    }

}
